/*
 * This file is part of Cadmium.
 * Copyright (C) 2007-2010 Xavier Clerc.
 *
 * Cadmium is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cadmium is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.x9c.cadmium.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * This class implements a thread copying data from an input stream to an
 * output stream.
 *
 * @author <a href="mailto:cadmium@x9c.fr">Xavier Clerc</a>
 * @version 1.0
 * @since 1.0
 */
public final class StreamCopyThread extends Thread {

    /** Size of internal buffer, in bytes. */
    private static final int BUFFER_SIZE = 1024;

    /** Output stream. */
    private final OutputStream out;

    /** Input stream. */
    private final InputStream in;

    /** Thrown exception. */
    private IOException exception;

    /**
     * Creates the thread but does not start it.
     * @param o output stream - should not be <tt>null</tt>
     * @param i input stream - should not be <tt>null</tt>
     */
    public StreamCopyThread(final OutputStream o, final InputStream i) {
        assert o != null : "null o";
        assert i != null : "null i";
        this.out = o;
        this.in = i;
    } // end constructor(OutputStream, InputStream)

    /**
     * Returns the exception thrown during copy, <tt>null</tt> if none.
     * @return the exception thrown during copy, <tt>null</tt> if none
     */
    public IOException getException() {
        return this.exception;
    } // end method 'getException()'

    /**
     * Copies data from input stream to output stream. <br/>
     * Copy is stopped if an exception is thrown, the exception can be
     * retrieved using {@link #getException()}. <br/>
     * Streams are not closed.
     */
    @Override
    public void run() {
        final byte[] buffer = new byte[StreamCopyThread.BUFFER_SIZE];
        try {
            int nb = this.in.read(buffer);
            while (nb != -1) {
                this.out.write(buffer, 0, nb);
                this.out.flush();
                nb = this.in.read(buffer);
            } // end while
            this.exception = null;
        } catch (final IOException ioe) {
            this.exception = ioe;
        } // end try/catch
    } // end method 'run()'

} // end class 'StreamCopyThread'
